package com.github.limit.fuse.spring.boot.persistence;

import com.github.limit.entity.LimitData;
import com.github.limit.persistence.AbstractAccessLimit;
import com.github.limit.util.LimitUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: wangdejun
 * @create: 2019-10-12 13:39
 **/
public class RedisAccessLimit extends AbstractAccessLimit {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取value
     *
     * @param key
     * @return
     */
    @Override
    public int doGetCount(String prefixKey, String key) {
        key = joinKey(prefixKey, key);
        Object value = redisTemplate.opsForValue().get(key);
        return Optional.ofNullable(value).map(val -> (int) val).orElse(0);
    }

    /**
     * 增加1
     *
     * @param key
     */
    @Override
    public void doIncrease(String prefixKey, String key) {
        key = joinKey(prefixKey, key);
        redisTemplate.opsForValue().increment(key);
    }

    /**
     * 根据前缀获取持久化的限流数据
     *
     * @param prefixKey
     * @return
     */
    @Override
    public List<LimitData> dataList(String prefixKey) {
        Set<String> keys = redisTemplate.keys(prefixKey + "*");
        return keys.stream().map(key -> new LimitData(key, getCount(key, ""))).collect(Collectors.toList());
    }

    private String joinKey(String prefixKey, String key) {
        return LimitUtils.replaceAndSbuLast(prefixKey + ":" + key);
    }
}
